package at.fhhgb.mc.android.mfb_hgb.activity;

import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import at.fhhgb.mc.android.mfb_hgb.R;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.ProgressDialog;
import at.fhhgb.mc.android.mfb_hgb.dal.SelectUser;
import at.fhhgb.mc.android.mfb_hgb.model.TaskCaller;
import at.fhhgb.mc.android.mfb_hgb.model.User;

public class LoginFragment extends Fragment implements TaskCaller {

	private ProgressDialog pDialog;
	private View rootView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_login, null);

		// Login-Button
		Button loginBtn = (Button) rootView.findViewById(R.id.button_login);
		loginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				doLogin();
			}

		});

		// "Done"-Key
		EditText passwordText = (EditText) rootView.findViewById(R.id.editText_password);
		passwordText.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					doLogin();
				}
				return true;
			}

		});

		return rootView;
	}

	private void doLogin() {
		pDialog = new ProgressDialog(getActivity());
		pDialog.show();

		String username = ((EditText) rootView.findViewById(R.id.editText_username)).getText().toString();
		String password = ((EditText) rootView.findViewById(R.id.editText_password)).getText().toString();

		if (username.isEmpty() || password.isEmpty()) {
			showErrorText(R.string.login_required);
		} else if (!isNetworkAvailable()) {
			showErrorText(R.string.no_network);
		} else {
			new SelectUser(this).execute(new BasicNameValuePair("Username", username), new BasicNameValuePair("Password", password));
		}
	}

	private void showErrorText(int errorTextID) {
		TextView errorText = (TextView) rootView.findViewById(R.id.textView_error);
		errorText.setText(getString(errorTextID));
		errorText.setVisibility(TextView.VISIBLE);

		pDialog.dismiss();
	}

	@Override
	public void onBackgroundTaskCompleted(Object result) {
		List<User> user = (List<User>) result;

		if (user == null) {
			showErrorText(R.string.login_invalid);
		} else {
			SharedPreferences prefs = getActivity().getSharedPreferences(getString(R.string.preferences_key), getActivity().MODE_PRIVATE);
			Editor editor = prefs.edit();

			editor.putString("username", user.get(0).getUsername());
			editor.putString("pwd", user.get(0).getPassword());
			editor.putLong("id", user.get(0).getUserID());
			editor.commit();

			Intent i = new Intent(getActivity(), OverviewActivity.class);
			getActivity().finish();
			startActivity(i);
		}

		pDialog.dismiss();
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
}
